package com.lagou.xml05;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.sql.*;

/**
 * @Author wsl
 * @Date 2021/8/24 22:17
 * @Project_Name mysql
 */
public class JDBCUtils {
    //1. 定义字符串变量, 记录获取连接所需要的信息
    private static String DRIVERNAME;
    private static String URL;
    private static String USER;
    private static String PASSWORD;

    //2.静态代码块
    static {
        try {
            //使用XPath读取 xml中的配置信息
            SAXReader sr = new SAXReader();

            Document document =
       sr.read("E:\\IdeaStudyProjects\\mysql\\xml_module2_3\\src\\com\\lagou\\xml05\\jdbc-config.xml");

            //获取属性name的值
            Node node = document.selectSingleNode("/jdbc/property[@name='driverClass']");
            DRIVERNAME = node.getText();
            URL = document.selectSingleNode("/jdbc/property[@name='jdbcUrl']").getText();
            USER = document.selectSingleNode("/jdbc/property[@name='user']").getText();
            PASSWORD = document.selectSingleNode("/jdbc/property[@name='password']").getText();

            //1.注册驱动
            Class.forName(DRIVERNAME);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    //3.获取连接的静态方法
    public static Connection getConnection(){
        try {
            //2.获取连接对象
            Connection con = DriverManager.getConnection(URL, USER, PASSWORD);
            return con;

        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //4.关闭的方法
    public static void close(Connection con, Statement statement, ResultSet resultSet){
        if (null != con && null != statement && null != resultSet){
            try {
                resultSet.close();
                statement.close();
                con.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
